package com.retirement.audit.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.retirement.activity.domain.OldActivity;
import com.retirement.activity.mapper.OldActivityMapper;
import com.retirement.audit.domain.OldAudit;
import com.retirement.audit.dto.OldAuditDto;
import com.retirement.audit.mapper.OldAuditMapper;
import com.retirement.audit.service.IOldAuditService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retirement.common.utils.SecurityUtils;
import com.retirement.common.utils.bean.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lijy
 * @since 2023-12-25
 */
@Service
public class OldAuditServiceImpl extends ServiceImpl<OldAuditMapper, OldAudit> implements IOldAuditService {

    @Resource
    private OldActivityMapper oldActivityMapper;

    @Override
    public <T> int addAudit(String dataId, String dataType, T t) {
        OldAudit bean = new OldAudit();
        BeanUtils.copyProperties(t,bean);
        bean.setId(IdUtil.simpleUUID());
        bean.setDataId(dataId).setDataType(dataType).setState("0")
                .setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now());

        return baseMapper.insert(bean);
    }

    @Override
    public List<OldAudit> listAudit(OldAuditDto dto) {
        return baseMapper.getList(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateAudit(OldAudit dto) throws IllegalArgumentException {
        OldAudit oldAudit = baseMapper.selectById(dto.getId());
        Assert.isTrue(ObjectUtil.isNotNull(oldAudit), "无该条记录");
        String result = "0";
        if(ObjectUtil.isNotEmpty(dto.getResult())){
            result = dto.getResult();
            oldAudit.setState("1");
        }else{
            throw new IllegalArgumentException("无结果状态");
        }
        oldAudit.setAuditorId(SecurityUtils.getUserId().toString())
                .setAuditorName(SecurityUtils.getUsername().toString())
                .setUpdateTime(LocalDateTime.now())
                .setResult(result)
                .setRemarks(dto.getRemarks());
        if(oldAudit.getDataType().equals("old_activity")){
            OldActivity oldActivity = oldActivityMapper.selectById(oldAudit.getDataId());
            oldActivity.setState(result);
            oldActivity.setStateTime(LocalDateTime.now());
            oldActivityMapper.updateById(oldActivity);
        }

        return baseMapper.updateById(oldAudit);
    }
}
